/*
* 添加受限空间作业
*
* */
import 'dart:convert';
import 'dart:typed_data';

import 'package:bruno/bruno.dart';
import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/api/task_api.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_input_widget.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/custom_select_widget.dart';
import 'package:center_beijing/widgets/selectRow_widget.dart';
import 'package:center_beijing/widgets/textarea_widget.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart' as Go;
import 'package:dio/dio.dart' as ImageForm;
import 'package:images_picker/images_picker.dart';
import 'package:http_parser/http_parser.dart';

class AddConfinedSpace extends StatefulWidget {
  const AddConfinedSpace();

  @override
  _AddConfinedSpaceState createState() => _AddConfinedSpaceState();
}

class _AddConfinedSpaceState extends State<AddConfinedSpace> {
  CustomLoading loading = CustomLoading.withMessage('提交中...');
  bool flag = false; //同意协议
  final TextEditingController projectName = TextEditingController(); //作业名称
  List<SelectItems> teamList = [];
  SelectItems selectTeam = SelectItems(); //选择班组
  List<SelectItems> partList = [];
  SelectItems selectPart = SelectItems(); //选择部门
  var content = '';
  var operation_time = '';
  List<String> tagList = []; //危险因素列表
  List dangerList = []; //危险因素所有对象列表

  List workList = []; //安全措施
  List<String> personSafeList = []; //个人防护器材列表
  List personSafeListAll = []; //个人防护器材所有对象列表
  Uint8List _paint; //签名
  List gasList = []; //气体检测检查项

  List<Media> photos = [];
  ImageForm.FormData formData;
  List passPhoto = [];

  List selectDanger = []; //选择的危险因素
  List selectPerson = []; //选择的个人防护

  var ownerSignId = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getAllDanger();
    this.getTeam();
    this.getSafe();
    this.getPerson();
    this.getGas();
    this.getPart();
  }

  /*
  * 获取危险因素
  * */
  getAllDanger() async {
    var result = await getDangerous({'codeType': 'BIM-TW-170'});
    if (result != null && result.length > 0) {
      List bbq = result.map((item) {
        return item['name'].toString();
      }).toList();
      this.setState(() {
        dangerList = result;
        tagList = bbq.cast();
      });
    }
  }

  /*
  * 获取班组
  * */
  getTeam() async {
    var result = await getWorkerTeamList({
      'projectSectionId': GlobalConfig.selectFactory.tag,
    });
    if (result != null && result.length > 0) {
      List<SelectItems> tem = [];
      result.forEach((element) {
        tem.add(SelectItems(label: element['teamName'], value: element['id']));
      });
      this.setState(() {
        teamList = tem;
      });
    }
  }

  /*
  * 获取部门
  * */
  getPart() async {
    var result = await getWorkerPartList({
      'projectSectionId': GlobalConfig.selectFactory.tag,
    });
    if (result != null && result.length > 0) {
      List<SelectItems> tem = [];
      result.forEach((element) {
        tem.add(SelectItems(label: element['name'], value: element['id']));
      });
      this.setState(() {
        partList = tem;
      });
    }
  }

  /*
  * 获取安全措施
  * */
  getSafe() async {
    var result = await getSafeStepDefList({
      'projectSectionId': GlobalConfig.selectFactory.tag,
    });
    if (result != null && result.length > 0) {
      this.setState(() {
        workList = result;
      });
    }
  }

  /*
  * 个人防护器材
  * */
  getPerson() async {
    var result = await getPersonSafeList({
      'codeType': 'BIM-TW-172',
    });
    if (result != null && result.length > 0) {
      List bbq = result.map((item) {
        return item['name'].toString();
      }).toList();
      this.setState(() {
        personSafeListAll = result;
        personSafeList = bbq.cast();
      });
    }
  }

  /*
  * 获取气体检测
  * */
  getGas() async {
    var result = await getGasList({
      'codeType': 'BIM-TW-171',
    });
    if (result != null && result.length > 0) {
      this.setState(() {
        gasList = result;
      });
    }
  }

  Future addImage() async {
    this.passPhoto = [];
    var tem = [];
    loading.show(delay: 30);
    for (var l = 0; l < workList.length; l++) {
      if (workList[l]['paint'] != null) {
        tem.add(l);
        passPhoto.add(workList[l]);
      }
    }
    if (this.passPhoto.length > 0) {
      formData = new ImageForm.FormData.fromMap({
        "tenantId": GlobalConfig.tenantId,
      });
      for (int i = 0; i < passPhoto.length; i++) {
        formData.files.add(MapEntry(
            "files",
            await ImageForm.MultipartFile.fromBytes(passPhoto[i]['paint'],
                filename: "bbq.jpg", contentType: MediaType('image', 'png'))));
      }
      formData.files.add(MapEntry(
          "files",
          await ImageForm.MultipartFile.fromBytes(_paint,
              filename: "bbq.jpg", contentType: MediaType('image', 'png'))));
      var result = await uploadImage(formData, GlobalConfig.tenantId);
      if (result != null && result.length > 0) {
        for (var i = 0; i < result.length; i++) {
          if (i == result.length - 1) {
            ownerSignId = result[i]['attachmentId'];
          } else {
            workList[tem[i]]['workSignId'] = result[i]['attachmentId'];
          }
        }
      }
    } else {}
    this.submit();
  }

  justifyInfo() {
    if (projectName.text == '') {
      Fluttertoast.showToast(msg: '请输入作业名称');
      return false;
    } else if (operation_time == '') {
      Fluttertoast.showToast(msg: '请选择作业时间');
      return false;
    } else if (selectTeam.label == null) {
      Fluttertoast.showToast(msg: '请选择作业班组');
      return false;
    } else if (this.selectPart.label == null) {
      Fluttertoast.showToast(msg: '请选择所属部门');
      return false;
    } else if (content == '') {
      Fluttertoast.showToast(msg: '请输入施工内容');
      return false;
    } else if (_paint == null) {
      Fluttertoast.showToast(msg: '请进行作业人签字');
      return false;
    }
    return true;
  }

  submit() async {
    for (var i = 0; i < selectDanger.length; i++) {
      dangerList[selectDanger[i]]['checkedTag'] = '1';
    }
    var pass = {
      'item': jsonEncode({
        'projectSectionId': GlobalConfig.selectFactory.tag,
        'workName': projectName.text,
        'teamId': selectTeam.value,
        'teamName': selectTeam.label,
        'workTime': operation_time,
        'deptId': selectPart.value,
        'deptName': selectPart.label,
        'workContent': content,
        'workStatus': '',
      }),
      'dangerFactors': jsonEncode(dangerList
          .map((e) => {
                'dangerName': e['name'],
                'dangerCode': e['code'],
                'dangerValue': e['name'],
                'checkedTag': e['checkedTag'] ?? '0'
              })
          .toList()), //危险因素
      'safeStepRecords': jsonEncode(workList //安全措施
          .map((e) => {
                'safeStepContent': e['safeStepContent'],
                'workSignId': e['workSignId'] ?? '',
                'workSignTime':
                    Utils.timeUtil(DateTime.now().toIso8601String()),
                'tutelageSignId': '',
                'tutelageSignTime':
                    Utils.timeUtil(DateTime.now().toIso8601String()),
              })
          .toList()),
      'equipRecords': jsonEncode(personSafeListAll.map((e) {
        //个人防护器材
        return {
          'equipName': e['name'],
          'equipCode': e['code'],
          'equipValue': e['name'],
          'checkedTag': selectPerson.contains(e['ordnum']) ? '1' : '0'
        };
      }).toList()),
      'gasRecords': jsonEncode(gasList
          .map((e) => {
                //气体检测
                'gasTitle': '气体检测',
                'gasName': e['name'],
                'gasCode': e['code'],
                'gasValue': e['input'] ?? '',
                'gasTime': Utils.timeUtil(DateTime.now().toIso8601String()),
                'rowNum': e['ordnum'],
              })
          .toList()),
      'ownerSignId': ownerSignId, //作业人签名
    };
    print(pass);
    var result = await addSpaceWork(pass);
    loading.dismiss();
    if (result != null) {
      Fluttertoast.showToast(msg: '提交成功');
      Go.Get.back(result: '成功');
      bus.emit('refreshHome');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('受限空间作业'),
        ),
        body: SafeArea(
          child: Container(
            padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).padding.bottom + 70),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    color: Colors.white,
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16),
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '基本信息',
                            style: TextStyle(
                                color: Styles.BlackColor,
                                fontSize: Styles.MainButtonTextFont,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                                      color: Styles.LineColor, width: 1))),
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8, Styles.spacing8, 0, 0),
                          child: CustomInput(
                            textFont: Styles.Middle15Font,
                            textAlign: TextAlign.right,
                            titleColor: Styles.TitleColor,
                            inputformat: [
                              LengthLimitingTextInputFormatter(10),
                            ],
                            title: '作业名称',
                            placeHold: '请输入',
                            textInput: this.projectName,
                            clearAll: false,
                            require: true,
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                          padding:
                              EdgeInsets.fromLTRB(Styles.spacing8, 0, 0, 0),
                          child: SelectRow(
                              titleFont: Styles.Middle15Font,
                              bottomLine: true,
                              titleColor: Styles.TitleColor,
                              require: true,
                              selectType: DateMode.YMDH,
                              title: '作业时间',
                              rightText: operation_time,
                              selectCallback: (value) {
                                this.setState(() {
                                  operation_time = value;
                                });
                              }),
                        ),
                        Container(
                          margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                                      color: Styles.LineColor, width: 1))),
                          child: CustomSelectWidget(
                            require: true,
                            titleFont: Styles.Middle15Font,
                            rightColor: selectTeam.label != null
                                ? Styles.DetailColor
                                : Styles.TitleColor,
                            rightText: selectTeam.label != null
                                ? selectTeam.label
                                : '请选择',
                            items: teamList,
                            selectCallback: (value) => this.setState(() {
                              selectTeam = value;
                            }),
                            title: '作业班组',
                            titleColor: Styles.TitleColor,
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                                      color: Styles.LineColor, width: 1))),
                          child: CustomSelectWidget(
                            require: true,
                            titleFont: Styles.Middle15Font,
                            rightColor: selectPart.label != null
                                ? Styles.DetailColor
                                : Styles.TitleColor,
                            rightText: selectPart.label != null
                                ? selectPart.label
                                : '请选择',
                            items: partList,
                            selectCallback: (value) => this.setState(() {
                              selectPart = value;
                            }),
                            title: '所属部门',
                            titleColor: Styles.TitleColor,
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                                      color: Styles.SpatLineColor, width: 1))),
                          margin: EdgeInsets.fromLTRB(Styles.spacing8,
                              Styles.spacing8, Styles.spacing8, 0),
                          // padding: EdgeInsets.fromLTRB(
                          //     Styles.spacing8, 0, Styles.spacing8, 0),
                          child: TextAreaWidget(
                            maxLength: 100,
                            labelText: '施工内容',
                            defaultValue: '',
                            placeholder: '请输入',
                            disabled: false,
                            required: true,
                            rows: 2,
                            titleFont: Styles.Middle15Font,
                            titleColor: Styles.TitleColor,
                            onChange: (value) => this.setState(() {
                              content = value;
                            }),
                          ),
                        ),
                        Container(
                          alignment: Alignment.centerLeft,
                          margin: EdgeInsets.fromLTRB(
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16),
                          child: Text(
                            '危险因素',
                            style: TextStyle(
                                color: Styles.TitleColor,
                                fontSize: Styles.Middle15Font),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(bottom: Styles.spacing16),
                          child: BrnSelectTag(
                              alignment: Alignment.center,
                              tags: tagList,
                              spacing: 20,
                              themeData: BrnTagConfig(
                                tagRadius: 12.0.r,
                              ),
                              isSingleSelect: false,
                              // initTagState: [true],
                              fixWidthMode: false,
                              onSelect: (selectedIndexes) {
                                selectDanger = selectedIndexes;
                                // BrnToast.show(selectedIndexes.toString(), context);
                              }),
                        )
                      ],
                    ),
                  ),
                  Container(
                    color: Colors.white,
                    margin: EdgeInsets.only(top: Styles.spacing16),
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16),
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '主要安全措施',
                            style: TextStyle(
                                color: Styles.BlackColor,
                                fontSize: Styles.MainButtonTextFont,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        ListView.builder(
                          physics: const NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemCount: workList.length,
                          itemBuilder: (BuildContext context, int index) {
                            //条目构建函数传入了index,根据index索引到特定图片
                            return Container(
                              decoration: BoxDecoration(
                                  border: Border(
                                      bottom: BorderSide(
                                          color: Styles.SpatLineColor,
                                          width: 1))),
                              padding: EdgeInsets.fromLTRB(Styles.spacing16,
                                  Styles.spacing16, Styles.spacing16, 0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text.rich(TextSpan(children: [
                                    TextSpan(
                                        text: "${(index + 1).toString()}、",
                                        style: TextStyle(
                                            color: Styles.BlackColor,
                                            fontSize: Styles.Middle15Font)),
                                    TextSpan(
                                        text:
                                            "${workList[index]['safeStepContent']}",
                                        style: TextStyle(
                                            color: Styles.BlackColor,
                                            fontSize: Styles.Middle15Font)),
                                  ])),
                                  Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0,
                                        Styles.spacing16,
                                        Styles.spacing16,
                                        Styles.spacing16),
                                    alignment: Alignment.centerLeft,
                                    color: Colors.white,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text.rich(TextSpan(children: [
                                          TextSpan(
                                              text: '作业人',
                                              style: TextStyle(
                                                  fontSize: Styles.Middle15Font,
                                                  color: Styles.TitleColor)),
                                        ])),
                                        GestureDetector(
                                          onTap: () async {
                                            print('签名');
                                            var result = await Go.Get.toNamed(
                                                RouteConfig.sign);
                                            if (result != null) {
                                              workList[index]['paint'] = result;
                                            }
                                            this.setState(() {});
                                          },
                                          child: Container(
                                            child: workList[index]['paint'] !=
                                                    null
                                                ? Image.memory(
                                                    workList[index]['paint'],
                                                    width: 80.w,
                                                    height: 30.h,
                                                  )
                                                : Icon(
                                                    Icons.mode_edit,
                                                    color: Styles.BlueColor,
                                                    size: Styles.MiddleFont17,
                                                  ),
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            );
                          },
                        ),
                        Container(
                          alignment: Alignment.centerLeft,
                          margin: EdgeInsets.fromLTRB(
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16),
                          child: Text(
                            '个人防护器材',
                            style: TextStyle(
                                color: Styles.TitleColor,
                                fontSize: Styles.Middle15Font),
                          ),
                        ),
                        BrnSelectTag(
                            alignment: Alignment.center,
                            tags: personSafeList,
                            spacing: 20,
                            themeData: BrnTagConfig(
                              tagRadius: 12.0.r,
                            ),
                            isSingleSelect: false,
                            // initTagState: [true],
                            fixWidthMode: false,
                            onSelect: (selectedIndexes) {
                              selectPerson = selectedIndexes;
                            }),
                        Container(
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16),
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '气体检测',
                            style: TextStyle(
                                color: Styles.BlackColor,
                                fontSize: Styles.MainButtonTextFont,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        ...gasList.map((e) {
                          return Container(
                            decoration: BoxDecoration(
                                border: Border(
                                    bottom: BorderSide(
                                        color: Styles.SpatLineColor,
                                        width: 1))),
                            margin:
                                EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                            padding: EdgeInsets.fromLTRB(
                                Styles.spacing8, 0, Styles.spacing8, 0),
                            child: CustomInput(
                              textAlign: TextAlign.right,
                              inputformat: [
                                LengthLimitingTextInputFormatter(10),
                              ],
                              titleColor: Styles.TitleColor,
                              title: e['name'],
                              placeHold: '请输入',
                              clearAll: false,
                              require: false,
                              textChange: (value) {
                                e['input'] = value;
                              },
                            ),
                          );
                        }).toList(),
                        Container(
                          margin: EdgeInsets.fromLTRB(Styles.spacing8,
                              Styles.spacing16, Styles.spacing8, 0),
                          child: RichText(
                              text: TextSpan(children: [
                            // WidgetSpan(
                            //   child: flag
                            //       ? Icon(
                            //           Icons.check_box,
                            //           color: Styles.BlueColor,
                            //           size: 16.0,
                            //         )
                            //       : Icon(
                            //           Icons.check_box_outline_blank,
                            //           color: Styles.GranColor,
                            //           size: 16.0,
                            //         ),
                            // ),
                            TextSpan(
                                text:
                                    ' 我已做好上述准备工作，被告知并确认了工作中的危险性，我将同监护人一起确认现场安全状况，检查个人防护用品及器材，保证不在危险状况下参与工作。',
                                style: TextStyle(
                                    fontSize: Styles.NormalFont,
                                    color: Styles.DetailColor),
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () {
                                    // this.setState(() {
                                    //   flag = !flag;
                                    // });
                                  }),
                          ])),
                        ),
                        Container(
                          margin: EdgeInsets.fromLTRB(
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16,
                              Styles.spacing16),
                          alignment: Alignment.centerLeft,
                          color: Colors.white,
                          child: Row(
                            // mainAxisAlignment:
                            // MainAxisAlignment.spaceBetween,
                            children: [
                              Text.rich(TextSpan(children: [
                                TextSpan(
                                    text: '作业人签名：',
                                    style: TextStyle(
                                        fontSize: Styles.Middle15Font,
                                        color: Styles.TitleColor)),
                              ])),
                              GestureDetector(
                                onTap: () async {
                                  print('签名');
                                  var result =
                                      await Go.Get.toNamed(RouteConfig.sign);
                                  if (result != null) {
                                    _paint = result;
                                  }
                                  this.setState(() {});
                                },
                                child: Container(
                                  child: _paint != null
                                      ? Image.memory(
                                          _paint,
                                          width: 80.w,
                                          height: 30.h,
                                        )
                                      : Icon(
                                          Icons.mode_edit,
                                          color: Styles.BlueColor,
                                          size: Styles.MiddleFont17,
                                        ),
                                ),
                              )
                            ],
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                FocusScope.of(context).requestFocus(new FocusNode());
                if (this.justifyInfo()) {
                  showDialog(
                      barrierDismissible: false,
                      context: this.context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: Text('注意'),
                          content: Text('确认提交吗？'),
                          actions: <Widget>[
                            new Container(
                              child: FlatButton(
                                child: new Text(
                                  "取消",
                                  style: TextStyle(color: Colors.black),
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                            ),
                            new Container(
                              child: FlatButton(
                                child: new Text(
                                  "确定",
                                  style: TextStyle(color: Colors.red),
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                  this.addImage();
                                  // this.submit();
                                },
                              ),
                            ),
                          ],
                        );
                      });
                }
              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '确定提交',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        ));
  }
}
